package io.renren.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @program: renren-security
 * @description: 随机数(字串)生成工具
 * @author: Lod_Yu
 * @create: 2018-09-28 13:50
 **/
public class RandomUtil {

    public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String NUMBER = "0123456789";
    public static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 返回一个定长的随机字符串(只包含大小写字母、数字)
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateString(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 返回一个7位的随机字符串(只包含大写字母、数字)前5位数为数字，后2位为大写字母
     *
     * @return 随机字符串
     */
    public static String generateSn() {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 7; i++) {
            if (i < 5) {
                sb.append(NUMBER.charAt(random.nextInt(NUMBER.length())));
            } else {
                sb.append(UPPERCASE.charAt(random.nextInt(UPPERCASE.length())));
            }
        }
        return sb.toString();
    }


    public static String generateOrderSN() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS" );
        // new Date()为获取当前系统时间，也可使用当前时间戳
        String date = df.format(new Date());
        return date.toString();
    }

    /**
     * 时间戳的8位随机数
     * @return
     */
    public static String createID() {
        byte[] lock = new byte[0];
        final long w = 1000000000;
        long r = 0;
        synchronized (lock) {
            r = (long) ((Math.random() + 1) * w);
        }
        return System.currentTimeMillis() + String.valueOf(r).substring(1);
    }

}
